package com.seo.controller.keyWord;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.github.pagehelper.PageInfo;
import com.seo.function.PageTool;
import com.seo.pojo.ReturnBody;
import com.seo.resolver.DefiniteException;
import com.seo.service.keyword.member.sdk.KeywordGMemberService;
import com.seo.service.keyword.sdk.KeywordGService;
import com.seo.service.sysUser.sdk.SysUserService;
import com.seo.utils.ClientConst;
import com.seo.utils.DateUtil;
import com.seo.utils.Jurisdiction;

import lombok.extern.slf4j.Slf4j;

/**
 * @ClassName: GoodsController
 * @author rtc
 * @version 2018.07.28 12:20
 */
@Slf4j
@Controller
@RequestMapping(value = "/keyWordG/")
public class KeyWordGController {
	
	@Autowired
	private KeywordGService keywordGService;
	
	@Autowired
	private SysUserService sysUserService;
	
	@Autowired
	private KeywordGMemberService keywordGMemberService;
	
	@Autowired
	private PageTool pageTool;

	/*
	 * 关键字列表
	 */
	@RequestMapping("/list")
	public String list(@RequestParam Map<String, Object> pam,HttpServletRequest request, HttpSession session) {
		log.info("进入关键字列表...");
		String userType = Jurisdiction.getT("userType", String.class);
		List<Map<String, Object>> venderList = keywordGService.getVenderList(); //厂商列表
		List<Map<String, Object>> engineList = keywordGService.getEngineList(); //搜索引擎列表
		List<Map<String, Object>> groupList = null;
		String userId = (String) pam.get("userId");
		if(StringUtils.isNotBlank(userId)){
			groupList = keywordGMemberService.getGroupByUserId(Integer.parseInt(userId));
		}
		//排名情况
		String ranking = (String) pam.get("ranking");
		if(StringUtils.isNotBlank(ranking)){
			String rankingStr = ranking.substring(0, ranking.indexOf("-"));
			String rankingState = ranking.substring(ranking.indexOf("-")+1);
			pam.put("rankingStr", Integer.valueOf(rankingStr));
			pam.put("rankingState", rankingState);
			pam.put("currentTime", DateUtil.getDay());
		}
		//排名区间 1：1-10 2：11-50 3： 51-100 4: 100+
		String rankingInterval = (String) pam.get("rankingInterval");
		if(StringUtils.isNotBlank(rankingInterval)) {
			String startRanking = null;
			String endRanking = null;
			if("1".equals(rankingInterval)) {
				startRanking = "1";
				endRanking = "10";
			}else if("2".equals(rankingInterval)) {
				startRanking = "11";
				endRanking = "50";
			}else if("3".equals(rankingInterval)) {
				startRanking = "51";
				endRanking = "100";
			}else {
				startRanking = "100";
			}
			pam.put("startRanking", startRanking);
			pam.put("endRanking", endRanking);
		}
		
		Integer id = Jurisdiction.getT("id", Integer.class, ClientConst.SESSION_USER);
		Map<String, Object> sysUser = sysUserService.getSysUserById(id);
		String dataAuthority = (String)sysUser.get("dataAuthority");
		if("00".equals(dataAuthority)) {
			pam.put("belongId", id);
		}
		
		PageInfo<?> page = pageTool.getAutoPage(keywordGService::getKeyWordsList,pam);
		request.setAttribute("page", page);
		request.setAttribute("venderList", venderList);
		request.setAttribute("engineList", engineList);
		request.setAttribute("pam", pam);
		request.setAttribute("groupList", groupList);
		request.setAttribute("userType", userType);
		return "keyWord/keyWord_list";

	}
	
	/**
	 * 关键字审核列表
	 * @param params
	 * @param request
	 * @param session
	 * @return
	 */
	@RequestMapping("/reviewList")
	public String reviewList(@RequestParam Map<String, Object> pam,HttpServletRequest request, HttpSession session) {
		log.info("进入关键词审核列表...");
		log.info("获取页面的传值userName: " + pam.get("userName") + "typeValue：" + pam.get("typeValue"));
		List<Map<String, Object>> engineList = keywordGService.getEngineList(); //搜索引擎列表
		Integer id = Jurisdiction.getT("id", Integer.class, ClientConst.SESSION_USER);
		Map<String, Object> sysUser = sysUserService.getSysUserById(id);
		String dataAuthority = (String)sysUser.get("dataAuthority");
		if("00".equals(dataAuthority)) {
			pam.put("belongId", id);
		}
		PageInfo<?> page = pageTool.getAutoPage(keywordGService::getKeyWordsReviewList,pam);
		log.info("关键词审核列表查询的数据：" + page);
		request.setAttribute("page", page);
		request.setAttribute("pam", pam);
		request.setAttribute("engineList", engineList);
		return "keyWord/keyWord_review_list";

	}
	
	
	@RequestMapping("/apiUpdateRanking")
	@ResponseBody
	public String apiUpdateRanking(@RequestParam String ids, @RequestParam boolean isAll, @RequestParam String apiType) {
		String userType = Jurisdiction.getT("userType", String.class);
		String userName = Jurisdiction.getT("userName", String.class);
		log.info("进入关键词批量更新,当前登录账户[{}]...", userName);
		if (!"01".equals(userType)) {
			throw new DefiniteException("权限不足");
		}
		Map<String, Object> params = new HashMap<>();
		params.put("ids", ids);
		params.put("isAll", isAll);
		params.put("apiType", apiType);
		
		log.info("进入关键词批量更新[{}]...", params);
		String msg = "";
		try {
			keywordGService.handelNewRankingByApi(params);
			msg = "true";
		} catch (Exception e) {
			log.error("异常：[{}]", e);
			msg = "error";
		}

		return msg;

	}
	
	@RequestMapping("/listByApi")
	@ResponseBody
	public ReturnBody listByApi(@RequestParam Long id) {
		if(id == null) {
			id = 0L;
		}
		ReturnBody rb = ReturnBody.init();
		Map<String, Object> params = new HashMap<>();
		params.put("id", id);
		params.put("num", 1000);
		
		List<Map<String, Object>> keyWordsList = keywordGService.getApiKeyWordsList(params);
		if(keyWordsList != null && keyWordsList.size() > 0) {
			rb.put("keyWordsList", keyWordsList);
			rb.put("maxId", keyWordsList.get(keyWordsList.size() - 1));
			return rb.success();
		}
		
		return rb.error();
		
	}
	
	@RequestMapping("/errorApiList")
	public String errorApiList(@RequestParam Map<String, Object> pam, HttpServletRequest request, HttpSession session) {
		log.info("进入api请求失败列表...");

		request.setAttribute("errorList", keywordGService.getApiErrorList());
		return "keyWord/keyWord_errorapi_list";

	}
	
	/**
	 * 批量删除 和 单独删除
	 * @param request
	 * @param session
	 * @return
	 */
	@RequestMapping("/delete")
	@ResponseBody
	public String delete(@RequestParam Map<String, Object> pam, HttpSession session) {
		log.info("进入关键词删除方法...");
		String msg = "";
		try {
			keywordGService.deleteArr(pam);
			msg = "true";
		} catch (Exception e) {
			msg = "error";
		}
		
		return msg;

	}

	/**
	 * 进入修改厂商页面
	 * @param userId
	 * @param request
	 * @return
	 */
	@RequestMapping("/edit")
	public String edit(@RequestParam Map<String, Object> pam, HttpServletRequest request) {
		log.info("进入编辑用户页面");
		List<Map<String, Object>> venderList = keywordGService.getVenderList();
		request.setAttribute("venderList", venderList);
		request.setAttribute("ids", pam.get("ids"));
		request.setAttribute("action", "editvender");
		return "keyWord/vender_edit";
	}
	
	@RequestMapping("/editvender")
	public String editvender(@RequestParam Map<String, Object> params, HttpServletRequest request) {
		log.info("修改厂商");
		ReturnBody rb = ReturnBody.init();
		rb = keywordGService.updateVender(params);
		request.setAttribute("result", rb.getResult());
		return "save_result";
	}
	
	/**
	 * 关键字审批
	 * @param pam
	 * @param session
	 * @return
	 */
	@RequestMapping("/keyWordReview")
	@ResponseBody
	public String keyWordReview(@RequestParam Map<String, Object> pam, HttpSession session) {
		log.info("进入关键词审批方法...");
		long a = System.currentTimeMillis();
		String msg = "";
		try {
			keywordGService.keyWordReview(pam);
			msg = "true";
		} catch (Exception e) {
			e.printStackTrace();
			msg = "error";
		}
		log.info("\r<br>执行耗时 : "+(System.currentTimeMillis()-a)/1000f+" 秒 ");
		return msg;
	}
	
	
	@RequestMapping("/toUpload")
	public String toUpload(@RequestParam Map<String, Object> pam, HttpServletRequest request) {
		log.info("进入导入关键词页面");
		return "keyWord/keyWord_import";
	}
	
	/**
	 * 导入
	 * @param file
	 * @return
	 */
	@RequestMapping("upload")
	public String importKeyWord(@RequestParam("file") MultipartFile file,@RequestParam Map<String, Object> pam,HttpServletRequest request){
		long a = System.currentTimeMillis();
		ReturnBody result = ReturnBody.init();
		String fileName = file.getOriginalFilename();
		String importTime = (String) pam.get("importTime");
		try {
			result.run(keywordGService.importKeyWord(fileName, file, importTime));
		} catch (Exception e) {
			e.printStackTrace();
		}
		request.setAttribute("result", result);
		request.setAttribute("importTime", importTime);
		log.info("\r<br>执行耗时 : "+(System.currentTimeMillis()-a)/1000f+" 秒 ");
		return "keyWord/keyWord_import";
	}
	
	/**
	 * 导出
	 * @param pam
	 * @param response
	 */
	@RequestMapping("export")
	public void exportKeyWord(@RequestParam Map<String, Object> pam,HttpServletResponse response){
		XSSFWorkbook workbook = new XSSFWorkbook();
		try {
			workbook = keywordGService.exportKeyWord(pam, response);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	
	/**
	 * 进入价格和类型修改页面
	 * @param userId
	 * @param request
	 * @return
	 */
	@RequestMapping("/editPricePage")
	public String editPricePage(@RequestParam Map<String, Object> pam, HttpServletRequest request) {
		log.info("进入价格和类型页面");
		request.setAttribute("targetRanking", pam.get("targetRanking"));
		request.setAttribute("price", pam.get("price"));
		request.setAttribute("ids", pam.get("ids"));
		request.setAttribute("action", "editPrice");
		return "keyWord/price_edit";
	}
	
	@RequestMapping("/editPrice")
	public String editPrice(@RequestParam Map<String, Object> params, HttpServletRequest request) {
		log.info("修改价格和类型");
		ReturnBody rb = ReturnBody.init();
		rb = keywordGService.updatePriceAndTargetRanking(params);
		request.setAttribute("result", rb.getResult());
		return "save_result";
	}
	
	/**
	 * 进入价格修改页面
	 * @param userId
	 * @param request
	 * @return
	 */
	@RequestMapping("/editPriceP")
	public String editPriceP(@RequestParam Map<String, Object> pam, HttpServletRequest request) {
		log.info("进入价格和类型页面");
		request.setAttribute("ids", pam.get("ids"));
		request.setAttribute("price", pam.get("price"));
		request.setAttribute("action", "editPrice");
		return "keyWord/price";
	}
	/**
	 * 启用停用
	 * @param pam
	 * @param session
	 * @return
	 */
	@RequestMapping("/keyWordEnable")
	@ResponseBody
	public String keyWordEnable(@RequestParam Map<String, Object> pam, HttpSession session) {
		log.info("进入关键词启用停用方法...");
		String msg = "";
		String oldState = (String) pam.get("oldState"); // 原来的状态
		String newState = (String) pam.get("newState"); // 现有的状态 也就是所要修改的状态
		if("01".equals(newState)){ // 如果现有状态 为01 使用中  那么原来的状态 必须为02 已停用
			if("02".equals(oldState)){
				pam.put("state", newState);
				try {
					keywordGService.updatekeyWordReviewDisabled(pam);
					msg = "true";
				} catch (Exception e) {
					msg = "error";
				}
			}
		}else if("02".equals(newState)){ // 如果现有状态 为02 已停用  那么原来的状态 必须为01  使用中
			if("01".equals(oldState)){
				pam.put("state", newState);
				try {
					keywordGService.updatekeyWordReviewDisabled(pam);
					msg = "true";
				} catch (Exception e) {
					msg = "error";
				}
			}
		}
		return msg;
	}
	
	/**
	 * 进入最初排名修改页面
	 * @param pam
	 * @param request
	 * @return
	 */
	@RequestMapping("/editInitRankingPage")
	public String editInitRankingPage(@RequestParam Map<String, Object> pam, HttpServletRequest request) {
		log.info("进入最初排名页面");
		request.setAttribute("initRanking", pam.get("initRanking"));
		request.setAttribute("ids", pam.get("ids"));
		request.setAttribute("action", "editInitRanking");
		return "keyWord/initRanking_edit";
	}
	/**
	 * 修改最初排名
	 * @param params
	 * @param request
	 * @return
	 */
	@RequestMapping("/editInitRanking")
	public String editInitRanking(@RequestParam Map<String, Object> params, HttpServletRequest request) {
		log.info("修改最初排名");
		ReturnBody rb = ReturnBody.init();
		rb = keywordGService.updatePriceAndTargetRanking(params);
		request.setAttribute("result", rb.getResult());
		return "save_result";
	}
	
	/**
	 * 进入最新排名修改页面
	 * @param pam
	 * @param request
	 * @return
	 */
	@RequestMapping("/editNewRankingPage")
	public String editNewRankingPage(@RequestParam Map<String, Object> pam, HttpServletRequest request) {
		log.info("进入最新排名页面");
		request.setAttribute("newRanking", pam.get("newRanking"));
		request.setAttribute("name", pam.get("name"));
		request.setAttribute("engine_code", pam.get("engine_code"));
		request.setAttribute("domain", pam.get("domain"));
		request.setAttribute("action", "editNewRanking");
		return "keyWord/newRanking_edit";
	}
	/**
	 * 修改最新排名
	 * @param params
	 * @param request
	 * @return
	 */
	@RequestMapping("/editNewRanking")
	public String editNewRanking(@RequestParam Map<String, Object> params, HttpServletRequest request) {
		log.info("修改最新排名");
		ReturnBody rb = ReturnBody.init();
		rb = keywordGService.updateNewRanking(params);
		request.setAttribute("result", rb.getResult());
		return "save_result";
	}
	
	/**
	 * 进入昨日排名修改页面
	 * @param pam
	 * @param request
	 * @return
	 */
	@RequestMapping("/editYesRankingPage")
	public String editYesRankingPage(@RequestParam Map<String, Object> pam, HttpServletRequest request) {
		log.info("进入昨日排名页面");
		request.setAttribute("newRanking", pam.get("newRanking"));
		request.setAttribute("name", pam.get("name"));
		request.setAttribute("engine_code", pam.get("engine_code"));
		request.setAttribute("domain", pam.get("domain"));
		request.setAttribute("run_time", pam.get("run_time"));
		request.setAttribute("action", "editYesRanking");
		return "keyWord/yesRanking_edit";
	}
	/**
	 * 修改昨日排名
	 * @param params
	 * @param request
	 * @return
	 */
	@RequestMapping("/editYesRanking")
	public String editYesRanking(@RequestParam Map<String, Object> params, HttpServletRequest request) {
		log.info("修改昨日排名");
		ReturnBody rb = ReturnBody.init();
		rb = keywordGService.updateYesRanking(params);
		request.setAttribute("result", rb.getResult());
		return "save_result";
	}
	
}
